
<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;
use fast\Http;
use think\Db;
use app\api\model\Weixin;
use app\admin\model\Addr;
use app\admin\model\Casefile;
use app\admin\model\Cases;
use app\admin\model\Que;
use PhpOffice\PhpWord\TemplateProcessor; 
use OSS\OssClient;
use OSS\Core\OssException;

use Dompdf\Dompdf;
use Dompdf\Options;
use Imagick;
/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third','ulogin','getphone','getuserbyphone','getq','renxiang','gettoali','setfile','pdf2png','eqpost','qianzi','getfileimg'];
    protected $noNeedRight = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third','ulogin','getphone','getuserbyphone','getq','gettoali','setfile','pdf2png','eqpost','qianzi','yugu','mycase','casedetail','getfileimg'];

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }
	public function ulogin(){
		$code=$this->request->post('code');
		$site=config('site')['mini'];
		//$weixin=new Weixin($site['appid'],$site['appsecret']);
		//$token=$weixin->getAccessToken();
		$url="https://api.weixin.qq.com/sns/jscode2session";
		$params=[
			'appid'=>$site['appid'],
			'secret'=>$site['appsecret'],
			'js_code'=>$code,
			'grant_type'=>'authorization_code'
		];
		$ret = Http::sendRequest($url, $params, 'GET');
        if ($ret['ret']) {
            $ar = json_decode($ret['msg'], true);
			$user=db('user')->where('openid',$ar['openid'])->find();
			if(empty($user)){
				//用户不存在   自动注册
				$usr['group_id']=1;
				$usr['username']="微信用户";
				$usr['nickname']="微信用户";
				$usr['status']="normal";
				$usr['avatar']="/assets/img/avatar.png";
				$usr['openid']=$ar['openid'];
				$uid=db('user')->insertGetId($usr);
			}else{
				$uid=$user['id'];
			}
             $duser = $this->auth->direct($uid);
			 $data = ['userinfo' => $this->auth->getUserinfo()];
			 $this->success(__('Logged in successful'), $data); 
        }
		return [];
	}
		//获取用户信息
	public function getinfo(){
		$user = $this->auth->getUser();
		$user->avatar=$this->qdomain($user->avatar,'a');
		
		$this->success('',$user);
	}
	//获取手机号
	public function getphone(){
		/*$code=$this->request->post('code');
		$site=config('site')['mini'];
		$weixin=new Weixin($site['appid'],$site['appsecret']);
		$token=$weixin->getAccessToken();
		$url="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=".$token['access_token'];
		$params = [
            'code'=>$code
        ];
		$params=json_encode($params);
		$ret = Http::sendRequest($url, $params, 'POST');
		 
        if ($ret['ret']) {
            $ar = json_decode($ret['msg'], true);
			if($ar['errcode']!==0){
				$this->error('授权失败，请重试');
			}
			if($ar['phone_info']['phoneNumber']){
				$this->getuserbyphone($ar['phone_info']['phoneNumber']);
			}else{
				$this->error('授权失败，请重试');
			}
        } 
		$this->error('授权失败，请重试');*/
		$this->getuserbyphone(18303412455);
	}
	public function getuserbyphone($mobile=""){
		if(empty($mobile)){
			return false;
		}
		$user=db('user')->where('mobile',$mobile)->find();
			if(empty($user)){
				//用户不存在   自动注册
				$usr['group_id']=1;
				$usr['username']="微信用户";
				$usr['nickname']="微信用户";
				$usr['status']="normal";
				$usr['avatar']="/assets/img/avatar.png";
				$usr['mobile']=$mobile;
				$uid=db('user')->insertGetId($usr);
			}else{
				$uid=$user['id'];
			}
		    $duser = $this->auth->direct($uid);
			 $data = ['userinfo' => $this->auth->getUserinfo()];
			 $this->success(__('Logged in successful'), $data); 
	}
	//处理图片路径 q去掉域名 a拼接域名 
	public function qdomain($img,$type="q"){
		if($type=='q'){
			if (strpos($img,request()->domain()) !== false) {
				$img=str_replace(request()->domain(),'',$img);
			}
		}else{
			if (strpos($img,'/uploads/') !== false&&strpos($img,'http')===false) {
				$img=request()->domain().$img;
			}
		}
		return $img;
	}
    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }
	
    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
	//实名认证
	public function shiming(){
		$sdata=$this->request->post();
		 
		if(empty($sdata['nickname'])){
			$this->error('姓名不能为空');
		}
		if(empty($sdata['cardno'])){
			$this->error('身份证号不能为空');
		}
		if(empty($sdata['addr'])){
			$this->error('需要填写地址');
		}
		//数据宝实名认证key 
		$url="https://api.chinadatapay.com/communication/personal/1882";
		$data['key']="87a3bfb66e65ebb8044a94531bf5017f";
		$data['name']=$sdata['nickname'];
		$data['idcard']=$sdata['cardno'];
		//$jdata= json_encode($data);
		$res = Http::post($url,$data);
       $res = json_decode($res,true);
			
		if($res['code']==10000&&$res['data']['result']==1){
			Db::startTrans();
			try {
				$user = $this->auth->getUser();
				$user->is_shi=1;
				$user->save();
				$shiming['user_id']=$this->auth->id;
				$shiming['name']=$sdata['nickname'];
				$shiming['cardno']=$sdata['cardno'];
				$shiming['addr']=$sdata['addr'];
				$shiming['seqNo']=$res['seqNo'];
				$shiming['createtime']=time();
				$uid=db('shiming')->insertGetId($shiming);
				Db::commit();
				$this->success('认证成功');
			} catch (Exception $e) {
				Db::rollback();
				$this->error($e->getMessage());
			}
		}elseif($res['code']==10000&&$res['data']['result']!=1){
			$this->error('验证失败：信息不一致');
		}else{
			$this->error('验证失败：'.$res['message']);
		}
		$this->error('验证失败');
	}
	//判断当前用户是否实名
	public function isshi(){
		$user=$this->auth->getUserinfo();
		if(empty($user)){
			$this->error('失败');
		}else{
			$this->success($user);
		}
		$this->error('失败');
	}
	//获取实名信息
	public function getshi(){
		$user=$this->auth->getUserinfo();
		if(empty($user)||$user['is_shi']!=1){
			$this->error('暂未实名');
		}else{
			$data=db('shiming')->where('user_id',$user['id'])->find();
			if(empty($data)){
				$this->error('信息为空');
			}else{
				$this->success($data);
			}
		}
	}
	public function addpt(){
		$adata=$this->request->post();
		
		 
		 if(empty($adata['name'])){
			 $this->error('请填写姓名');
		 }
		  if(empty($adata['addr'])){
			 $this->error('请填写地址');
		 }
		  if(empty($adata['tel'])){
			 $this->error('请填写手机号');
		 }
		 
		if (!Validate::regex($adata['tel'], "^1\d{10}$")){
            $this->error('请填写正确的手机号');
        }
	
		$adata['user_id']=$this->auth->id;
		$adata['updatetime']=time();
 
		$adata['is_default']=$adata['is_default']=="true"?1:0;
		
		Db::startTrans();
		try {
			if($adata['is_default']==1){
				db('addr')->where('user_id',$this->auth->id)->setField('is_default',0);
			}
			if(isset($adata['id'])){
				$aid=db('addr')->update($adata);	
			}else{
				$adata['createtime']=time();
				$aid=db('addr')->insertGetId($adata);	
			}
			Db::commit();
			$this->success('保存成功');
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
		$this->error('保存失败');
	}
	//地址列表
	public function getaddr(){
		
		$list=Addr::where('user_id',$this->auth->id)->select();
		$this->success('请求成功',$list);
	}
	//地址详情
	public function getadteail(){
		$aid=input('aid');
		$data=Addr::find($aid);
		$data['is_default']=$data['is_default']==1?true:false;
		$this->success('请求成功',$data);
	}
	//地址删除
	public function dela(){
		$aid=input('aid');
		$data=db('addr')->delete($aid);
	 
		$this->success('操作成功',$data);
	}
	//资料提交
	public function ziliaop(){
		$sdata = $this->request->post();  
		$sdata['lqpdata']=html_entity_decode($sdata['lqpdata']);
		
		$sdata['lqpdata']=json_decode($sdata['lqpdata'],true);
		$sdata['lqjson']=json_encode($sdata['lqpdata']);
		unset($sdata['lqpdata']);
		$sdata['sqr']=html_entity_decode($sdata['sqr']);
		 
		$sdata['sqr']=json_decode($sdata['sqr'],true);
		$sqr=array(
			'name'=>$sdata['sqr']['name'],
			'cardno'=>$sdata['sqr']['cardno'],
			'addr'=>$sdata['sqr']['addr']
		);
		$sdata['sqrjson']=json_encode($sqr);
		unset($sdata['sqr']);
		if(!empty($sdata['pys'])){
			$sdata['pys']=html_entity_decode($sdata['pys']);
			$sdata['pys']=json_decode($sdata['pys'],true);
			$zys=array();
			foreach($sdata['pys'] as $k=>$v){
				$zys[$k]['que']=$v['que']['name'];
				foreach($v['ans'] as $k1=>$v1){
					$zys[$k]['ans'][$k1]=array(
						'title'=>$v1['title'],
						'value'=>$v1['value']
					);
				}
			}
			$sdata['ysjson']=json_encode($zys);
			unset($sdata['pys']);
		}
		
		
		$sdata['user_id']=$this->auth->id;
		$sdata['createtime']=time();
		$sdata['caseno']='ray_'.date('ymdhis',time()).rand(1000,9999).substr(uniqid(),7,4);
		Db::startTrans();
		try {
			$cid=db('cases')->insertGetId($sdata);
			Db::commit();
			$this->success('提交成功',$cid);
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		} 
	}
	//获取附件列表
	public function getcfile(){
		$cid=input('cid');
		$case=Cases::find($cid);
		 
		if(empty($case)){
			$this->error('信息不存在');
		}
		if($case['user_id']!=$this->auth->id){
			$this->error('无权限');
		}
		$list=Casefile::where('affair_id',$case['affair_id'])->select();
		$this->success('请求成功',$list); 
	}
	//提交案件附件
	public function pupdata(){
		$sdata = $this->request->post();
		$case=db('cases')->find($sdata['cid']);
		if(empty($case)){
			$this->error('信息不存在');
		}
		if($case['user_id']!=$this->auth->id){
			$this->error('无权限');
		}
		$sdata['filesjson']=html_entity_decode($sdata['pdata']);
		$sdata['filesjson']=json_decode($sdata['filesjson'],true);
		$case['filesjson']=json_encode($sdata['filesjson']);
		$case['state']=12;
		Db::startTrans();
		try {
			$aid=db('cases')->update($case);	
			Db::commit();
			$this->success('操作成功');
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		} 
	}
	public function getque(){
		$tque=db('que')->field('que,ans')->select();
	
		$cid=input('cid'); 
		$case=db('cases')->find($cid);
		
		if(empty($case)){
			$this->error('信息不存在');
		}
		if($case['user_id']!=$this->auth->id){
			$this->error('无权限');
		}
		$case['affair']=db('affair')->find($case['affair_id']);
		$narray=$this->getq($case['affair']['name']);
		$case['ysjson']=json_decode($case['ysjson'],true);
		$str='';
		foreach($case['ysjson'] as $k=>$v){
			$str.=$v['que'].'为:';
			foreach($v['ans'] as $k1=>$v1){
				$str.=$v1['title'].":".$v1['value'].";";
			}
		}
		 
		$case['sqrjson']=json_decode($case['sqrjson'],true);
		$birth= strlen($case['sqrjson']['cardno'])==15?('19'.substr($case['sqrjson']['cardno'],6,6)):substr($case['sqrjson']['cardno'],6,8);
		$case['sqrjson']['birth']=substr($birth,0,4).'年'.substr($birth,4,2).'月'.substr($birth,6,2).'日';
		$case['sqrjson']['sex']=  substr($case['sqrjson']['cardno'],(strlen($case['sqrjson']['cardno']))==15?-2:-1)%2?'男':'女';
		
		$arr3=array(
			array(
				'que'=>'你要求申报什么公证事项',
				'ans'=>"我要申办{$case['affair']['name']}"
			),
			array(
				'que'=>'你要求申办这些公证有何用途？在哪里使用？',
				'ans'=>"用于{$case['syd']}{$case['yt']}使用"
			),
			array(
				'que'=>'你的姓名、性别、住址、出生日期、身份证号',
				'ans'=>"我叫{$case['sqrjson']['name']}，性别:{$case['sqrjson']['sex']}，住址：{$case['sqrjson']['addr']}，出生日期:{$case['sqrjson']['birth']}，身份证号:{$case['sqrjson']['cardno']}"
			),
			array(
				'que'=>'请讲一讲与公证事项相关的情况',
				'ans'=>"我为了去{$case['syd']}{$case['yt']}使用，需要办理{$case['affair']['name']}，{$str}"
			)
			 
		);
		$zarray=array_merge($tque,$arr3,$narray);
		$this->success('请求成功',$zarray);
	}
	
	//返回询问笔录最后的确认问题（固定）
	public function getq($afname){
		$narray=array(
			array(
				'que'=>'我公证处指定在线公证员为你办理公证，你是否要求回避？',
				'ans'=>'我不要求回避。'
			),
			array(
				'que'=>"（1）本次公证服务内容为{$afname} 公证，我处按照法律规定和司法部指定的“公证书格式”出具《公证书》；（2）出具《公证书》的期限为受理公证申请之日起十五个工作日内（但因不可抗力、补充证明材料和需要核实有关情况所需要时间不计算在上述期限内）；（3）我们将按照根据山西省公证服务收费标准收取公证费用。公证费用待审核通过后另行通知。",
				'ans'=>"我知道了。"
			),
			array(
				'que'=>'你提交给公证处的所有材料都是真实的吗？你的上述陈述都是真实的吗？办理公证是你的真实意愿吗',
				'ans'=>'我提交的材料都是真实的。我申请公证行为系自愿所为，没有受到胁迫，没有重大误解，没有恶意串通，我对申请公证的后果清楚无误'
			),
			array(
				'que'=>'请你核对本笔录，如果有疑问，可以通过视频方式要求修改、补充笔录。',
				'ans'=>'好的 我没有修改意见了。'
			),
			array(
				'que'=>'如果你对本笔录没有疑义或者异议，请在本笔录上进行电子签名',
				'ans'=>'我同意在本笔录上进行电子签名，也同意在申请表、照片页、告知书等公证材料上进行电子签名。'
			)
		);
		return $narray;
	}
	//询问记录提交
	public function ptwen(){
		$sdata=$this->request->post();
		$case=db('cases')->find($sdata['cid']);
		if(empty($case)){
			$this->error('信息不存在');
		}
		if($case['user_id']!=$this->auth->id){
			$this->error('无权限');
		} 
		  
		$pdata=html_entity_decode($sdata['pdata']);
		 
		$pdata=json_decode($pdata,true);
		$case['quejson']=json_encode($pdata);
		$case['state']=13;
		Db::startTrans();
		try {
			$aid=db('cases')->update($case);	
			Db::commit();
			$this->success('操作成功');
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		} 
		 
	}
	//人像比对
	public function renxiang(){
		$sdata=$this->request->post();
		$case=db('cases')->find($sdata['cid']);
		if(empty($case)){
			$this->error('信息不存在');
		}
		if($case['user_id']!=$this->auth->id){
			$this->error('无权限');
		} 
			//数据宝实名认证key 
		$url="https://api.chinadatapay.com/communication/personal/2061";
		$data['key']="aa8bb857a5e2daaee6c0301e4c4497d7";
		$sqr=json_decode($case['sqrjson'],true);
		$data['name']=$sqr['name'];
		$data['idcard']=$sqr['cardno'];
		$data['imageId']=$sdata['backImg'];
		$jdata= json_encode($data);
		$res = Http::post($url,$data);
		$res = json_decode($res,true);
		 
		if($res['code']==10000){
			$imageUrl="https://h5live.chinadatapay.com:29000/cdp/h5live/".$sdata['backImg'];
			$as=$this->gettoali($imageUrl);
			if($as){
				$case['he_image']=$as['url'];
				$case['bak_image']=$as['bak_url'];
				$case['he_time']=date('Y-m-d');
				$case['he_code']=$res['data']['score'];
				$case['state']=14;
				Db::startTrans();
				try {
					$aid=db('cases')->update($case);	
					Db::commit();
					$this->success('操作成功');
				} catch (Exception $e) {
					Db::rollback();
					$this->error($e->getMessage());
				} 
			}else{
				$this->error('验证失败');
			}
		}else{
			$this->error('验证失败');
		}	
		$this->error('验证失败');
	}
	//把照片上传到阿里云
	public function gettoali($imageUrl=''){
		
		$savePath="uploads/tmp";
		if (!is_dir($savePath)) {
            @mkdir($savePath, 0755, true);
        }
		$savePath=$savePath.'/'.date('ymdhis',time()).rand(1000,9999).substr(uniqid(),7,4).".jpg";
        
		$imageData = file_get_contents($imageUrl);
 		
		$saved = file_put_contents($savePath, $imageData); 
		if($saved){	
			$file=realpath($savePath);
			$ftype=substr($savePath,strrpos($savePath,'.')+1);
			$aliyunoss=config('site')['aliyunoss'];
			$ossClient = new OssClient($aliyunoss['AccessKeyId'],$aliyunoss['AccessKeySecret'],$aliyunoss['endpoint']);

			$bucket = $aliyunoss['bucket']; // 存储桶名称  
			try{
				$ax=$ossClient->uploadFile($bucket,$savePath, $file);
				 
				//unlink($file);
				$back['url']=$ax['info']['url'];
				$back['bak_url']=$savePath;
				return $back;
			}catch(OssException $e){
				return false;
			} 
		}else{
			return false;
		}
		return false;
	}
	
	 //word文档生成方法
	public function setfile_bak($cid=0){
		header('Content-Type: text/html; charset=utf-8');
		$cid=6;
		$case=db('cases')->find($cid);
		/*if(empty($case)){
			$this->error('信息不存在');
		}
		if($case['user_id']!=$this->auth->id){
			$this->error('无权限');
		} */
		$que=json_decode($case['quejson']);
		$questr="";
		foreach($que as $k=>$v){
			$questr.="问：".$v->que."<br/><br/>";
			$questr.="答：".$v->answer."<br/><br/>";
		}
		$users=db('user')->field('mobile')->find($case['user_id']);
		$case['sqrjson']=json_decode($case['sqrjson'],true);
		$birth= strlen($case['sqrjson']['cardno'])==15?('19'.substr($case['sqrjson']['cardno'],6,6)):substr($case['sqrjson']['cardno'],6,8);
		$case['sqrjson']['birth']=substr($birth,0,4).'年'.substr($birth,4,2).'月'.substr($birth,6,2).'日';
		$case['sqrjson']['sex']=  substr($case['sqrjson']['cardno'],(strlen($case['sqrjson']['cardno']))==15?-2:-1)%2?'男':'女';
		$sqrj="{$case['sqrjson']['name']}，{$case['sqrjson']['sex']}，{$case['sqrjson']['birth']}出生，住址：{$case['sqrjson']['addr']}，公民身份证号码：{$case['sqrjson']['cardno']}，联系电话：{$users['mobile']}。";
		 
		$bm_path = "static/template/".date('Ymd').'/'.$cid.'/';
		if (!file_exists($bm_path)){
		   mkdir ($bm_path,0777,true);  // 如果保存目录不存在就创建新目录
		}
		
		//询问笔录
		$templateProcessor = new TemplateProcessor('static/template/que.docx');
		$templateProcessor->setValue('caseque', $questr);
		$templateProcessor->setValue('casesqr', $sqrj);
		$templateProcessor->setValue('caseno', $case['caseno']);
		$templateProcessor->setValue('casetime', date('Y-m-d'));
		//$templateProcessor->cloneRowAndSetValues('name0',$res[$d]['data']);
		$quefile = $bm_path.'que.docx';
		$templateProcessor->saveAs($quefile); //另存为新word文档，根据模板和变量生成了新的文档
	}
	//生成pdf文件 多个文件方法 备份
	public function setfile_bakduo($cid=0){
		$cid=input('cid');
		$case=db('cases')->find($cid);
		if(empty($case)){
			$this->error('信息不存在');
		}
		if($case['user_id']!=$this->auth->id){
			$this->error('无权限');
		}
		$farr=array(
			0=>'shenqing',
			1=>'shouli',
			2=>'gaozhi',
			3=>'que',
			4=>'heyan'
		);
		//保存路径
		$bm_path = "static/template/".date('Ymd').'/'.$cid.'/';
		if (!file_exists($bm_path)){
		   mkdir ($bm_path,0777,true);  // 如果保存目录不存在就创建新目录
		}
		$img=array();
		foreach($farr as $k=>$v){
			// 创建一个PDF对象  
			$options = new Options();
			$options->set('isRemoteEnabled',true); 
			$dompdf = new Dompdf($options);
			$htmlContent=file_get_contents(url('index/zaixian/zaixain',array('cid'=>$cid,'type'=>$v),'html',true));
			$dompdf->loadHtml($htmlContent);
			$dompdf->setPaper('A4','portrait');
			$dompdf->render();
			$pdfContent=$dompdf->output();
			file_put_contents($bm_path.$v.'.pdf', $pdfContent);
			$barr=$this->pdf2png($bm_path.$v.'.pdf',$bm_path,$v);
			$img=array_merge($img,$barr);
		}
		if(empty($img)){
			$this->error('获取失败');
		}else{
			$this->success('获取成功',$img);
		}
	}
	//生成pdf
	public function setfile($cid=0){
		$cid=input('cid');
		$case=db('cases')->find($cid);
		if(empty($case)){
			$this->error('信息不存在');
		}
		if($case['user_id']!=$this->auth->id){
			$this->error('无权限');
		}
		//保存路径
		$bm_path = "static/template/".date('Ymd').'/'.$cid.'/';
		if (!file_exists($bm_path)){
		   mkdir ($bm_path,0777,true);  // 如果保存目录不存在就创建新目录
		}
		$img=array();
		$options = new Options();
		$options->set('isRemoteEnabled',true); 
		$dompdf = new Dompdf($options);
		$hh=url('index/zaixian/zuhe',array('cid'=>$cid),'html',true);
		$hh=str_replace('https','http',$hh);
		 
		$htmlContent=file_get_contents($hh);
		$dompdf->loadHtml($htmlContent);
		$dompdf->setPaper('A4','portrait');
		$dompdf->render();
		$pdfContent=$dompdf->output();
		file_put_contents($bm_path.'zuhe.pdf', $pdfContent);
		$barr=$this->pdf2png($bm_path.'zuhe.pdf',$bm_path,'zuhe');
		$img=array_merge($img,$barr);
		if(empty($img)){
			$this->error('获取失败');
		}else{
			$this->success('获取成功',$img);
		}
	}
	//pdf转图片
	public function pdf2png($pdf='',$path='',$pre='',$page=-1)
    {
		$path =  $path.'img';
		if (!file_exists($path)){
		   mkdir ($path,0777,true);  // 如果保存目录不存在就创建新目录
		}
        if(!extension_loaded('imagick'))
        {
            return false;
        }
        if(!file_exists($pdf))
        {
            echo dirname($pdf);
            echo "file not exit";
            return false;
        }
		$im = new Imagick();
        $im->setResolution(120,120);
        $im->setCompressionQuality(70); 
		try {
			if($page==-1){
				$im->readImage($pdf);
			}else{
				$im->readImage($pdf."[".$page."]");
			}
		}catch (\Exception $e) {
			echo $e->getMessage();
			die;
		}
        foreach ($im as $Key => $Var)
        {
            $Var->setImageFormat('png');
            $filename=$path."/".$pre.'_'.$Key.'.png';
            if($Var->writeImage($filename) == true)
            {
                $Return[] =$this->request->domain().'/'.$filename;
            }
        }
		return $Return;
    }
	//获取和创建用户id
	
	public function getacid(){
		$shiming=db('shiming')->where('user_id',$this->auth->id)->find();
		 
		if($shiming['accountId']){
			 $this->success('请求成功',$shiming['accountId']);
		}else{
			$data['name']=$shiming['name'];
			$data['idNo']=$shiming['cardno'];
			$url='http://8.131.61.73:8080/tech-sdkwrapper/timevale/account/addPerson';
			$res=$this->eqpost($data,$url);
			$ret=json_decode($res,true);
			if($ret['errCode']==0){
				$shiming['accountId']=$ret['accountId'];
				db('shiming')->update($shiming);
				$this->success('请求成功',$ret['accountId']);
			}else{
				$this->error($ret['msg']);
			}	
		}
		$this->error("请重试");
	}
	//e签宝签署接口
	public function qianzi(){
		
		$sdata=$this->request->post();
	
		$cid=$sdata['cid'];
		$case=db('cases')->find($cid);
		if(empty($case)){
			$this->error('信息不存在');
		}
		if($case['user_id']!=$this->auth->id){
			$this->error('无权限');
		}
		if($case['state']!=14){
			$this->error('状态有误');
		}
		$bm_path = "static/template/".date('Ymd').'/'.$cid.'/';
		if (!file_exists($bm_path)){
		   mkdir ($bm_path,0777,true);  // 如果保存目录不存在就创建新目录
		}
		$savepath =  $bm_path.'qian';
		if (!file_exists($savepath)){
		   mkdir ($savepath,0777,true);  // 如果保存目录不存在就创建新目录
		}
		$shiming=db('shiming')->where('user_id',$this->auth->id)->find();
		if(empty($shiming)){
			$this->error('实名信息为空');
		}
		if(empty($shiming['accountId'])){
			$this->error('实名信息为空');
		}
		$data['signType']="Key";
		$data['accountId']=$shiming['accountId'];
		$data['sealData']=$sdata['code'];
		 
		$data['file']=array(
			"srcPdfFile"=>realpath($bm_path.'zuhe.pdf'),
			"dstPdfFile"=>realpath($savepath.'/')
		);
		$data['signPos']=array(
			"posType"=>1,
			"key"=>'签署栏',
			"width"=>80,
			"posX"=>100
		);
		$url='http://8.131.61.73:8080/tech-sdkwrapper/timevale/sign/userFileSign';
		$res=$this->eqpost($data,$url);
		
		$ret=json_decode($res,true);
		if($ret['errCode']==0){
			Db::startTrans();
			try {
				$case['qian_file']=substr($ret['dstFilePath'],strrpos($ret['dstFilePath'],'static'));
				$case['state']=0;
				db('cases')->update($case);
				Db::commit();
				$this->success('操作成功');
			} catch (Exception $e) {
				Db::rollback();
				$this->error($e->getMessage());
			}
			
		}else{
			$this->error($ret['msg']);
		}
		
		 
	}
//e签宝发送数据接口
	public function eqpost($data=array(),$url=''){
		$headers = array(  
			'Content-Type: application/json;charset=UTF-8',
		);  
		$jdata= json_encode($data);
		// 发送POST请求  
		$ch = curl_init();  
		curl_setopt($ch, CURLOPT_URL, $url);  
		curl_setopt($ch, CURLOPT_POST, true); 
		curl_setopt($ch, CURLOPT_POSTFIELDS,$jdata);  		
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);  
		$response = curl_exec($ch);  
		curl_close($ch); 
		return $response;
	}
//预估费用
	public function yugu(){
		$cid=input('cid');
		$case=db('cases')->find($cid);
		if(empty($case)){
			$this->error('信息不存在');
		}
		if($case['user_id']!=$this->auth->id){
			$this->error('无权限');
		}
		if($case['state']>10){
			$this->error('状态有误');
		}
		$case['affair']=db('affair')->find($case['affair_id']);
		$case['ziqu']=config('site')['ziqu'];
		$case['sqrjson']=json_decode($case['sqrjson'],true);
		$case['createtime']=date('Y-m-d',$case['createtime']);
		$this->success('请求成功',$case);
	}
	//案件列表
	public function mycase(){
		$map['user_id']=$this->auth->id;
		$map['state']=input('state')?input('state'):0;
		$list=db('cases')->where($map)->order('id','desc')->select();
		$aid=array();
		foreach($list as $k=>$v){
			$list[$k]['createtime']=date('Y-m-d',$v['createtime']);
			$aid[]=$v['affair_id'];
		}
		$affairs=db('affair')->where('id','in',$aid)->column('name','id');
		$data['affairs']=$affairs; 
		$data['list']=$list;
		$this->success('请求成功',$data);
	}
	//案件详情
	public function casedetail(){
		$cid=input('cid');
		$case=db('cases')->find($cid);
		if(empty($case)){
			$this->error('信息不存在');
		}
		if($case['user_id']!=$this->auth->id){
			$this->error('无权限');
		}
		$case['affair']=db('affair')->find($case['affair_id']);
		$case['ziqu']=config('site')['ziqu'];
		$case['sqrjson']=json_decode($case['sqrjson'],true);
		$case['filesjson']=json_decode($case['filesjson'],true);
		$case['lqjson']=json_decode($case['lqjson'],true);
		$lq='';
		foreach($case['lqjson'] as $k=>$v){
			$lq.=$v;
		}
		$case['lq']=$lq;
		$case['ysjson']=json_decode($case['ysjson'],true);
		$this->success('请求成功',$case);
	}
	//文档处理
	public function getfileimg(){
		$cid=input('cid');
		$case=db('cases')->find($cid);
		if(empty($case)){
			$this->error('信息不存在');
		}
		if($case['user_id']!=$this->auth->id){
			$this->error('无权限');
		}
		if(empty($case['qian_file'])){
			$this->error('文件不存在');
		}
		
		if($case['is_qian']!=1){
			$bm_path = "static/template/".date('Ymd').'/'.$cid.'/';
			$barr=$this->pdf2png($case['qian_file'],$bm_path,'qian');
			if(empty($barr)){
				$this->error('文件不存在');
			}
			$case['shenqing_images']=json_encode(array($barr[0]));
			$case['shouli_images']=json_encode(array($barr[1]));
			$case['gaozhi_images']=json_encode(array($barr[2],$barr[3]));
			$case['que_images']=json_encode(array($barr[4],$barr[5]));
			$case['heyan_images']=json_encode(array($barr[6]));
			$case['is_qian']=1;
			db('cases')->update($case);
		}	
		$type=input('type')?input('type'):"shenqing";
		$img=json_decode($case[$type.'_images'],true);
		 
		$this->success('请求成功',$img);
	}
	//撤销案件
	public function casexiao(){
		$cid=input('cid');
		$case=db('cases')->find($cid);
		if(empty($case)){
			$this->error('信息不存在');
		}
		if($case['user_id']!=$this->auth->id){
			$this->error('无权限');
		}
		if($case['state']==4||$case['state']==5){
			$this->error('该案件不能撤回');
		}
		Db::startTrans();
		try {
			$case['state']=8;
			db('cases')->update($case);
			Db::commit();
			$this->success('操作成功');
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
	}
}

